#include <QApplication>
#include <QMessageBox>
#include "mainwindowimpl.h"
#include "classes.h"
#include "cubaturs.h"

bool createConnection();
bool calculation(Cubaturs *,int);

int main(int argc, char ** argv)
{
	QApplication app( argc, argv );
        if (!createConnection()) {
                QMessageBox::critical(0, qApp->tr("Cannot open database"),
                                      qApp->tr("Unable to establish a database connection.\n"
                                                      "Click Cancel to exit."), QMessageBox::Cancel);
                return 1;
            }
        if (QCoreApplication::argc()>1)
        {
            if (QCoreApplication::arguments().at(1)=="--nogui")
            {
                QString str;
                int method;
                str=QCoreApplication::arguments().at(3);
                method=str.toInt();
                str=QCoreApplication::arguments().at(2);
                Cubaturs ft(str,method);
                calculation(&ft,method);
            }
            else return 1;
            return 0;
        }
        MainWindowImpl win;
        win.show();
        app.connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) );
	return app.exec();
}

bool createConnection()
{
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("waveBase");
        if (!db.open()) return false;
        return true;
}

bool calculation(Cubaturs *ft, int method)
{
    __complex__ double bufRES[9], EIt;
    gsl_complex EItog[3], vectorE;
    double ampl,arg;
    GSL_SET_COMPLEX(&vectorE,0,0);
    ft->calc(1,method);
    for (int i=0; i<9; i++) bufRES[i]=ft->RES[i];
    ft->calc(2,method);
    for (int i=0; i<9; i++) bufRES[i]+=ft->RES[i];
    for (int i=0; i<3; i++)
    {
        EIt=bufRES[i]+bufRES[i+3]+bufRES[i+6];
        GSL_SET_COMPLEX(&EItog[i],__real__(EIt),__imag__(EIt));
    }
    for (int i=0;i<3;i++) vectorE=gsl_complex_add(vectorE,gsl_complex_pow_real(EItog[i],2));
    vectorE=gsl_complex_sqrt(vectorE);
    ampl=gsl_complex_abs(vectorE);	//Amplitude
    arg=gsl_complex_arg(vectorE);
    /*! filling output */
    QString str,fileName="NeFeR_output.csv";
    QFile writeFile(fileName);
    QTextStream stream(&writeFile);
    if(writeFile.open(QIODevice::WriteOnly))
    {
        stream << str.setNum(GSL_REAL(vectorE))+"\n";
        stream << str.setNum(GSL_IMAG(vectorE))+"\n";
        stream << str.setNum(ampl)+"\n";
        stream << str.setNum(arg)+"\n";
    }
    writeFile.close();
    return 1;
}
